﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Read.API.Command.MenuCommand;
using B.S.BaseData.Read.API.DTO;
using MediatR;

namespace B.S.BaseData.Read.API.CommandHandler.MenuHandler
{
    public class QueryMenuHandler : IRequestHandler<QueryMenuCommand, APIResult<List<MenuDTO>>>
    {
        private readonly IBaseRepository<Menu> menuRep;
        private readonly IMapper mapper;

        public QueryMenuHandler(IBaseRepository<Menu> menuRep,IMapper mapper)
        {
            this.menuRep = menuRep;
            this.mapper = mapper;
        }
        public Task<APIResult<List<MenuDTO>>> Handle(QueryMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<MenuDTO>> result = new APIResult<List<MenuDTO>>();
            var list = from a in menuRep.GetAll().Where(x => !x.IsDeleted)
                       select new MenuDTO
                       {
                           MenuId = a.MenuId,
                           MenuName = a.MenuName,
                           MenuUrl = a.MenuUrl,
                           PId = a.PId,
                           CreateUser = a.CreateUser,
                           CreateTime = a.CreateTime,
                           UpdateUser = a.UpdateUser,
                           UpdateTime = a.UpdateTime,
                           IsDeleted = a.IsDeleted,
                            OrderNum = a.OrderNum,
                           ParentName = (from b in menuRep.GetAll()
                                         where b.MenuId == a.PId
                                         select new Menu
                                         {
                                             MenuName = b.MenuName,
                                         }).Distinct().FirstOrDefault()

                       };
            list = list.OrderBy(x => x.OrderNum);
            result.Code=APIEnum.Success;
            result.Msg = "查询成功";
            result.Data=mapper.Map<List<MenuDTO>>(list);
            return Task.FromResult(result);
        }
    }
}
